import { rename } from 'fs'
import { basePath } from './config'
import { PlayListItem } from './type'
import { readPlaylist, writePlaylist } from './utils'

/**
 * @param {string} playlist 列表名称
 * @param {string} dirName 目录名称
 * @param {boolean} renameRom 是否重命名文件
 */
export async function renamePlaylist(
  playlist: string,
  dirName = playlist,
  renameRom = false
) {
  const data = await readPlaylist(playlist)

  data.items = data.items.map(item => {
    const { label: oldLabel, path: oldPath } = item
    const label = oldLabel
      .replace(/^\d+\s+/g, '')
      .replace(/\s+(\d+)$/g, '$1')
      .replace(/[：|\-|\_]/g, ' ')
      .replace(/^(RPG|HACK|修改版) /g, '')
      .replace(/\s+/g, ' ')
    const ext = oldPath.slice(oldPath.lastIndexOf('.')).toLowerCase()

    const file = label + ext
    const oldFilePath = oldPath.replace(/^./g, basePath).replace(/\\+/g, '/')
    // const oldFileName =
    // oldPath.slice(oldPath.lastIndexOf('\\') + 1, oldPath.lastIndexOf('.')) + ext
    const filePath = `${basePath}/rom/${dirName}/${file}`

    /** 根据列表名称重命名 rom 文件 */
    if (renameRom && oldFilePath !== filePath) {
      // 重命名为旧的名称
      // rename(filePath, `../rom/${dirName}/${oldFileName}`, function (err) {
      rename(oldFilePath, filePath, function (err) {
        if (err) {
          console.error(err)
        } else {
          console.log(
            `重命名rom：${oldFilePath.replace(/\.\.rom\//g, '')} => ${file}`
          )
        }
      })
    }

    /** 根据列表名称重命名缩略图 */
    if (oldLabel !== label) {
      rename(
        `${basePath}/thumbnails/${dirName}/Named_Snaps/${oldLabel}.png`,
        `${basePath}/thumbnails/${dirName}/Named_Snaps/${label}.png`,
        function (err) {
          if (err) {
            console.error(err)
          } else {
            console.log(`重命名缩略图：${oldLabel}.png => ${label}.png`)
          }
        }
      )
    }

    return new PlayListItem({
      path: renameRom ? `.\\rom\\${dirName}\\${file}` : item.path,
      label,
      core_path: item.core_path,
      core_name: item.core_name,
      db_name: dirName
    })
  })

  await writePlaylist(playlist, data)

  console.log(`游戏列表“${playlist}”已重命名完成`)
}
